package com.example.nacos;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;

import java.util.List;
import java.util.Random;

public class RandomServiceInstanceChooser implements ServiceInstanceChooser {
    private final DiscoveryClient discoveryClient;
    private final Random random;

    public RandomServiceInstanceChooser(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
        this.random = new Random();
    }


    @Override
    public ServiceInstance choose(String serviceId) {
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceId);
        return serviceInstances.get(random.nextInt(serviceInstances.size()));
    }

    @Override
    public <T> ServiceInstance choose(String serviceId, Request<T> request) {
        return null;
    }
}
